#include "qelib.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS.h"
#include "queue.h"



static void cmd_start(void)
{

	BaseType_t ret;
	uint8_t ipaddrs[4] = {0, 0, 0, 0};
	uint8_t netmask[4] = {255, 255, 255, 0};
	uint8_t gateway[4] = {192, 168, 3, 1};
	uint8_t dnsaddr[4] = {0,0,0,0};
	uint8_t macaddr[6] = {0xB0,0x22,0x22,0x22,0x22,0x22};
	ret = FreeRTOS_IPInit(ipaddrs, netmask, gateway, dnsaddr, macaddr);
	qe_printf("IPInit ret:%d\r\n", ret);
}
QE_SHELL_EXPORT_CMD_EXEC(tcpip, cmd_start, tcpip start command);

static void cmd_ifconfig(void)
{
	uint32_t ip = FreeRTOS_GetIPAddress();
	char string[16] = {'\0'};
	qe_printf("IP : 0x%x\r\n", ip);
}
QE_SHELL_EXPORT_CMD_EXEC(ifconfig, cmd_ifconfig, ifconfig command);

QueueHandle_t xPingReplyQueue;

static int cmd_ping(char *dst)
{
	char *ips = "192.168.31.126";
	uint32_t ulIPAddress;
	uint32_t ulIntervalMs = 1000;
	uint16_t usRequestSequenceNumber, usReplySequenceNumber;

	xPingReplyQueue = xQueueCreate(1, sizeof(uint16_t));

	ulIPAddress = FreeRTOS_inet_addr(ips);
	qe_printf("ip 0x%x\r\n", ulIPAddress);
	usRequestSequenceNumber = FreeRTOS_SendPingRequest(ulIPAddress, 4, 2000 / portTICK_PERIOD_MS);
	if (usRequestSequenceNumber == pdFAIL) {
		qe_printf("ping failed\r\n");
	} else {
		if( xQueueReceive( xPingReplyQueue,
			&usReplySequenceNumber,
			2000 / portTICK_PERIOD_MS ) == pdPASS ) {
				if( usRequestSequenceNumber == usReplySequenceNumber ) {
					qe_printf("ping success\r\n");
				}
			}

	}
	return 0;
}
QE_SHELL_EXPORT_CMD_FUNC(1, ping, cmd_ping, ping command);

void vApplicationPingReplyHook( ePingReplyStatus_t eStatus, uint16_t usIdentifier )  
{  
	qe_printf("vApplicationPingReplyHook\r\n");
    switch( eStatus )  
    {  
        case eSuccess:
            /* A valid ping reply has been received. Post the sequence number  
               on the queue that is read by the vSendPing() function below. Do  
               not wait more than 10ms trying to send the message if it cannot be  
               sent immediately because this function is called from the TCP/IP  
               RTOS task - blocking in this function will block the TCP/IP RTOS task. */  
            xQueueSend(xPingReplyQueue, &usIdentifier, 10 / portTICK_PERIOD_MS );  
            break;  
  
        case eInvalidChecksum :  
        case eInvalidData :  
            /* A reply was received but it was not valid. */  
            break;  
    }  
}  
